import React from 'react'
import PropTypes from 'prop-types'
import Paper from '@material-ui/core/Paper';
import DateTextCell from '../TextField/DateTextCell'
import TimeTextCell from '../TextField/TimeTextCell'
import EnhancedTableToolbar from './EnhancedTableToolbar'
import Loading from '../Loading/loading'
import {getListFunc, getSearchFunc, deleteFunc, editFunc, BatchDeleteFunc } from './Ajax/ajax'
import {
    SortingState,
    IntegratedSorting,
    PagingState,
    IntegratedPaging,
    EditingState,
    IntegratedFiltering,
    SelectionState,
    IntegratedSelection,
    CustomPaging
} from '@devexpress/dx-react-grid';
import {
    Grid,
    Table,
    TableHeaderRow,
    PagingPanel,
    TableEditRow,
    TableEditColumn,
    ColumnChooser,
    TableColumnVisibility,
    Toolbar,
    TableSelection,
    TableColumnResizing
} from '@devexpress/dx-react-grid-material-ui';

let dateColumns = []
let timeColumns = []

const EditCellComponent = (props) => {
    const {column} = props
    const name = column.name
    if (dateColumns.indexOf(name) !== -1) {
        return <DateTextCell {...props} />
    } else if (timeColumns.indexOf(name) !== -1) {
        return <TimeTextCell {...props} />
    }
    else {
        return <TableEditRow.Cell {...props} />;
    }

};

class CustomTable extends React.Component {
    state = {
        selection: [],
        loading:true,
        currentPage:0,
        totalCount: 0,
        pageSize: 10,
        rows:[],
    }

    componentWillMount() {
        dateColumns = this.props.dateColumns
        timeColumns = this.props.timeColumns
    }

    componentDidMount() {
        const {pageSize, currentPage} = this.state
        this.getList(pageSize, currentPage)
    }

    getListCallBack = (data) => {
        const rows = data.rows
        const totalCount = data.totalCount
        if(Object.prototype.toString.call(rows) === '[object Array]') {
            this.setState({rows, loading:false, totalCount})
        }
    }

    errorCallBack = () => {
        this.setState({loading:false})
    }

    getList = (pageSize, currentPage) => {
        const { getListUrl } = this.props
        if(!pageSize && pageSize !== 0) {
            pageSize = this.state.pageSize
        }
        if(!currentPage && currentPage !== 0) {
            currentPage = this.state.currentPage
        }
        const params = {}
        if( pageSize !== 0) {
            params.limit = pageSize
            params.offset = pageSize * currentPage
            getListFunc(getListUrl, params, this.getListCallBack, this.errorCallBack)
        }else {
            getListFunc(getListUrl, params, this.getListCallBack, this.errorCallBack)
        }
    }

    deleteRow = (row) => {
        const { deleteUrl } = this.props
        deleteFunc(deleteUrl, row, this.getList, this.errorCallBack)
    }

    commitChanges = ({added, changed, deleted}) => {
        const { rows } = this.state
        if (added) {
            console.log(added)
        }
        if (changed) {
            console.log(changed)
        }
        if (deleted) {
            this.deleteRow(rows[deleted[0]])
        }
    }

    changeSearchValue(searchValue) {
        console.log(searchValue)
    }

    changeCurrentPage = currentPage => {
        this.setState({
            loading: true,
            currentPage,
        })
        this.getList(this.state.pageSize, currentPage)
    }
    changePageSize = pageSize => {
        this.setState({
            loading: true,
            pageSize
        })
        this.getList(pageSize, this.state.currentPage)
    }

    changeSelection = selection => {
        this.setState({selection});
    }

    render() {
        const {selection, loading, currentPage, pageSize, rows, totalCount} = this.state
        const {columns, columnExtensions, Sorting, pageSizes, defaultColumnWidths, title} = this.props
        Toolbar.RootProps = {
            title: title,
            numSelected: selection.length
        }
        return (
            <Paper style={{ position: 'relative' }}>
                <Grid
                    rows={rows}
                    columns={columns}>
                    {Sorting === true ? <SortingState/> : null}
                    {Sorting === true ? <IntegratedSorting/> : null}
                    <SelectionState
                        selection={selection}
                        onSelectionChange={this.changeSelection}
                    />
                    <PagingState
                        defaultCurrentPage={0}
                        defaultPageSize={10}
                        currentPage={currentPage}
                        onCurrentPageChange={this.changeCurrentPage}
                        pageSize={pageSize}
                        onPageSizeChange={this.changePageSize}
                    />
                    <CustomPaging
                        totalCount={totalCount}
                    />
                    <EditingState
                        onCommitChanges={this.commitChanges}
                    />
                    <IntegratedSelection/>
                    <IntegratedPaging/>
                    <IntegratedFiltering/>

                    <Table
                        columnExtensions={columnExtensions}
                        message={{noData: '暂无数据'}}
                    />
                    <TableColumnResizing defaultColumnWidths={defaultColumnWidths} />
                    <TableHeaderRow showSortingControls={Sorting}/>
                    <TableEditRow cellComponent={EditCellComponent}/>
                    <TableEditColumn showAddCommand
                                     showEditCommand
                                     showDeleteCommand
                                     messages={{
                                         addCommand: '添加',
                                         editCommand: '修改',
                                         deleteCommand: '删除',
                                         commitCommand: '保存',
                                         cancelCommand: '取消'
                                     }}
                    />
                    < PagingPanel pageSizes={pageSizes}
                                  messages={{showAll: '全部', rowsPerPage: '行数'}}
                    />

                    <TableSelection showSelectAll/>

                    <TableColumnVisibility messages={{noColumns: '无显示列'}}/>
                    <Toolbar rootComponent={EnhancedTableToolbar} selection={selection}></Toolbar>
                    <ColumnChooser/>
                </Grid>
                {loading && <Loading />}
            </Paper>
        )
    }
}

CustomTable.defaultProps = {
    dateColumns: [],
    pageSizes: [5,10,15,30,0]
}
CustomTable.propTypes = {
    rows: PropTypes.array,
    columns: PropTypes.array,
    columnExtensions: PropTypes.array,
    defaultCurrentPage: PropTypes.number,
    pageSize: PropTypes.number,
    Sorting: PropTypes.bool,
    dateColumns: PropTypes.array,
    timeColumns: PropTypes.array,
    pageSizes: PropTypes.array,
    defaultColumnWidths:PropTypes.array,
    title: PropTypes.string,
    getListUrl: PropTypes.string,//查询url
    getSearchUrl: PropTypes.string, //搜索url
    editUrl: PropTypes.string, //修改url
    deleteUrl: PropTypes.string, //删除url
    batchDeleteUrl: PropTypes.string, //批量删除url
}
export default CustomTable